package mqtt

import (
	"encoding/json"
	"fmt"
	"iot-base/common/config"
	"sync"
	"time"

	MQTT "github.com/eclipse/paho.mqtt.golang"
)

func reRegisterWithPattern(taddr string) {
	fmt.Println("reRegisterWithPattern---------enter lock")
	registerArrayLock.RLock()
	for _, rg := range registerInfos {
		if rg.mqttAddr == taddr {
			client := GetClient(rg.mqttAddr)
			if client != nil {
				fmt.Println("get client----------------subscribe--------------------", rg.pattern)
				client.Subscribe(rg.pattern, 0, rg.frameCallback)
			}
		}
	}
	registerArrayLock.RUnlock()
	fmt.Println("reRegisterWithPattern---------enter leave lock")
}

var registerArrayLock = new(sync.RWMutex)
var registerInfos = make([]registerInfo, 0, 5)

type registerInfo struct {
	mqttAddr string
	pattern  string
	//callback FunCmdHandler
	frameCallback func(client MQTT.Client, msg MQTT.Message)
}

//RegisterWithPattern 注册事件，key为带有+或*的
func RegisterWithPattern(mqttAddr string, pattern string, callback FunCmdHandler) {
	if callback == nil {
		return
	}
	if mqttAddr == "" {
		mqttAddr = config.MQTTOption.Addr
	}
	fmt.Println("register pattern 1", pattern)
	rg := registerInfo{mqttAddr: mqttAddr, pattern: pattern,
		frameCallback: func(client MQTT.Client, msg MQTT.Message) {

			topic := msg.Topic()
			payload := msg.Payload()
			//fmt.Println("enter fun", topic)
			if payload != nil {
				cmd := Cmd{}
				err := json.Unmarshal(payload, &cmd)

				if err == nil && cmd.CmdType != "" && time.Now().Unix()-cmd.TimeStamp < 300 {
					callback(client, topic, &cmd)
				} else {
					fmt.Println("pro give up", err, cmd)
				}
			}
		},
	}
	registerArrayLock.Lock()
	registerInfos = append(registerInfos, rg)
	registerArrayLock.Unlock()
	client := GetClient(mqttAddr)
	if client != nil {
		fmt.Println("register pattern", pattern)
		client.Subscribe(pattern, 0, rg.frameCallback)
	}
}
